/**
* Created by wangshuyi on 4/20/2017, 3:45:24 PM.
*/

'use strict';

const extend = require('extend');

const express = require('express');
const router = express.Router();

const logger = require('log4js').getLogger("sys");

const resUtil = require("../../module/util/resUtil");
const reqUtil = require("../../module/util/reqUtil");

const service = require("../../service/article/BookcaseService");
const ArticleService = require("../../service/article/ArticleService");
const FileService = require("../../service/system/tool/FileService");

/* GET users listing. */
//列表
router.post('/list', function(req, res, next) {
    let condition = req.body, query = req.query,
    populate = '';
    condition = reqUtil.formatCondition(condition);

    service
        .findForPage(req.session.userData, query.pageSize, query.pageNumber, condition, populate)
        .then(function (data) {
            res.send(resUtil.success(data));
        }, function (err) {
            res.send(resUtil.error({}));
        });
});
router.get('/tree', function(req, res, next) {
    let condition = req.query;
    condition = reqUtil.formatCondition(condition);

    service
        .tree(req.session.userData, '', condition)
        .then(function (data) {
            res.send(resUtil.success(data));
        }, function (err) {
            res.send(resUtil.error({}));
        });
});

//所有
router.post('/find', function(req, res, next) {
    let condition = req.body, query = req.query,
    populate = '', sort = {'sort':1};
    condition = reqUtil.formatCondition(condition);

    service
        .find(req.session.userData, condition, populate, sort)
        .then(function (data) {
            res.send(resUtil.success({rows:data}));
        }, function (err) {
            res.send(resUtil.error({}));
        });
});
//查看目录banner
router.get('/findBanner', function(req, res, next) {
    let ids  = req.query.ids;
    let arr = ids.split(',');
    let count = 0;
    let result=[];
    for(let i=0;i<arr.length;i++){
        FileService
            .find({},{_id:arr[i]})
            .then(data=>{
                    count++;
                    result.push(data)
                    if(count==arr.length) {
                        res.send(resUtil.success({data:result}))
                    }},
                err=>{ res.send(resUtil.error())}
            )
    }
});
//更新
router.post('/save/:id', function(req, res, next) {
    let data = req.body;
    let _id = req.params.id;

    data.updater = req.session.userData._id;

    service
        .updateById(req.session.userData, _id, data)
        .then(function (data) {
            res.send(resUtil.success({data:data}));
        }, function (err) {
            res.send(resUtil.error({}));
        });
});
//新增
router.post('/save', function(req, res, next) {
    let data = req.body;
    data.creater = req.session.userData._id;
    data.updater = req.session.userData._id;

    service
        .save(req.session.userData, data)
        .then(function (data) {
            res.send(resUtil.success({data:data}));
        }, function (err) {
            res.send(resUtil.error({}));
        });
});
//删除
router.get('/remove/:id', function(req, res, next) {
    let _id = req.params.id;
    let removeByUpdate = (__id)=>{
        return new Promise((resolve,reject)=>{
            let allPromise = [];
            service.find(req.session.userData,{parent:__id}).then(bookcaseList=>{
                if(bookcaseList){
                    bookcaseList.forEach(child=>{
                        allPromise.push(removeByUpdate(child._id))
                    })
                }
                Promise.all(allPromise).then(()=>{
                    let selfPromise=[];
                    selfPromise.push(service.updateById(req.session.userData,__id,{state:0}));
                    selfPromise.push(ArticleService.update(req.session.userData,{bookcase:__id},{state:0},{multi:true}));
                    Promise.all(selfPromise).then(result=>{
                        resolve();
                    },err=>reject(err))
                },err=>{reject(err)})
            })
        })
    };

    removeByUpdate(_id).then(
        data => res.send(resUtil.success({})),
        err=>  res.send(resUtil.error({}))
    );
});

//批量删除
router.post('/remove', function(req, res, next) {
    let body = req.body;
    let condition = {
    _id : {"$in" : body.ids}
    };

    service
        .remove(req.session.userData, condition)
        .then(function (data) {
            res.send(resUtil.success({data:data}));
        }, function (err) {
            res.send(resUtil.error({}));
        });
});
//详情
router.get('/detail/:id', function(req, res, next) {
    let _id = req.params.id;
    let populate = 'parent';

    service
        .findById(req.session.userData, _id, populate)
        .then(function (data) {
            res.send(resUtil.success({data:data}));
        }, function (err) {
            res.send(resUtil.error({}));
        });
});


module.exports = router;



